package com.aoxun.core.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

public class CameraUtils {
	
	private static final String DevKey="cos_ft";
	private static final String SecretId="TeZzCn4l6DxussTax478gYU7a8tGW+3ymE+LsUd6kIc=";
	private static final String SecretKey="puup77rWH8HxculKK6jJuz1VAM2hE4kHiY3zpF5iuAw=";
	
	private static final String scssUrl="http://cgi.scss.dnsv1.com";

	public static String getSignStr(String urlPath,long time) {
		
		System.out.println(urlPath);
		String signPath=DevKey+urlPath+SecretId+SecretKey+time;
		
		String sign=getSHA256Str(signPath);
		System.out.println(sign);
		
		return sign;
	}
	
	/***
     *  利用Apache的工具类实现SHA-256加密
     * @param str 加密后的报文
     * @return
     */
    public static String getSHA256Str(String str){
        MessageDigest messageDigest;
        String encdeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
            encdeStr = Hex.encodeHexString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encdeStr;
    }
    
    
    /**
     * httpGet 请求 获取签名
     * @param urlPath   组装获取签名的字符串
     * @return
     * @throws Exception
     */
	public static JSONObject httpGetSignStr(String method,String urlPath,Map<String, String> parmsMap) throws Exception {
		
		long time=Calendar.getInstance().getTimeInMillis();

		
		String urlParams=urlParamterStringer(parmsMap);
		
		String sign=getSignStr(method+urlPath,time);
		
		HttpGet httpRequst = new HttpGet(scssUrl+urlPath+"?"+urlParams);
		httpRequst.setHeader("Authorization", "dk="+DevKey+"&ak="+SecretId+"&st="+time+"&sign="+sign);    
		String callResult="";
		try {
			HttpResponse httpResponse = HttpClientBuilder.create().build().execute(httpRequst);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				
				HttpEntity httpEntity = httpResponse.getEntity();
				callResult = EntityUtils.toString(httpEntity);
				//对返回字符串进行转码
				callResult= new String(callResult.getBytes(),"UTF-8");

				System.out.println(callResult);
				
			} else {
				JSONObject jsonResult=new JSONObject();
				jsonResult.put("code", "99");
				jsonResult.put("message", "接口请求失败");
				return jsonResult;
			}
		} catch (Exception e) {
			JSONObject jsonResult=new JSONObject();
			jsonResult.put("code", "99");
			jsonResult.put("message", "接口请求异常");
			return jsonResult;
		}
		return JSONObject.parseObject(callResult);
	}
	
	 /**
     * httpGet 请求 获取签名
     * @param urlPath   组装获取签名的字符串
     * @return
     * @throws Exception
     */
	public static JSONObject httpPostSignStr(String method,String urlPath,Map<String, String> parmsMap) throws Exception {
		
		long time=Calendar.getInstance().getTimeInMillis();
		
		String urlParams=urlParamterStringer(parmsMap);
		
		String sign=getSignStr(method+urlPath,time);
		
		HttpPost httpRequst = new HttpPost(scssUrl+urlPath+"?"+urlParams);
		httpRequst.setHeader("Authorization", "dk="+DevKey+"&ak="+SecretId+"&st="+time+"&sign="+sign);    
		String callResult="";
		try {
			HttpResponse httpResponse = HttpClientBuilder.create().build().execute(httpRequst);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				
				HttpEntity httpEntity = httpResponse.getEntity();
				callResult = EntityUtils.toString(httpEntity);
				//对返回字符串进行转码
				callResult= new String(callResult.getBytes(),"UTF-8");

				System.out.println(callResult);
				
			} else {
				JSONObject jsonResult=new JSONObject();
				jsonResult.put("code", "99");
				jsonResult.put("message", "接口请求失败");
				return jsonResult;
			}
		} catch (Exception e) {
			JSONObject jsonResult=new JSONObject();
			jsonResult.put("code", "99");
			jsonResult.put("message", "接口请求异常");
			return jsonResult;
		}
		return JSONObject.parseObject(callResult);
	}
	
	 /** 
	   * 将map中的数据格式化成服务端所需的表单String(www.baidu.com/login?userName=lambdroid&password=123456的“？”以及之后的数据) 
	   *  
	   * @param head 
	   *            url头部字串，一般为“？”，在表单方式中分隔URL和请求参数map 
	   * @param map 
	   *            请求参数map 
	   * @return 格式化完成后的表单数据 
	   */  
	  public static <K, V> String urlParamterStringer(Map<K, V> map)  
	  {  
	      if (map == null || map.isEmpty())  
	      {  
	          return "";  
	      }  
	  
	      int capacity = map.size() * 30;       //设置表单长度30字节*N个请求参数  
	  
	      //参数不为空，在URL后面添加head（“？”）  
	      StringBuilder buffer = new StringBuilder(capacity);  
	      /*if (!map.isEmpty())  
	      {  
	          buffer.append(head);            
	      }  */
	  
	      //取出Map里面的请求参数，添加到表单String中。每个参数之间键值对之间用“=”连接，参数与参数之间用“&”连接  
	      Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();  
	      while (it.hasNext())  
	      {  
	          Map.Entry<K, V> entry = it.next();  
	          Object key = entry.getKey();  
	          buffer.append(key);  
	          buffer.append('=');  
	          Object value = entry.getValue();  
	          buffer.append(value);  
	          if (it.hasNext())  
	          {  
	              buffer.append("&");  
	          }  
	      }  
	      return buffer.toString();  
	  }  
	
	public static void main(String[] args) throws Exception  {
		long da=Calendar.getInstance().getTimeInMillis();
		
		/*Map<String, String> map=new HashMap<>();
		map.put("offset", "0");
		map.put("rows", "123");
		System.out.println(httpGetSignStr("get","/api/device-groups",map));*/
		
		Map<String, String> map2=new HashMap<>();
		map2.put("name", "admin_zooming");
		map2.put("password", "ziz99$88");
		System.out.println(httpPostSignStr("post","/api/users/login",map2));

	}
}
